using System.Net;

namespace AnalyStock.DataManage;

public static class HttpClientUtility
{
    public static async Task<string> HttpClientPostAsync(Uri uri, object datajson)
    {
        //在使用GB2312编码前需要先使用Encoding.RegisterProvider方法注册
        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        using HttpClient httpClient = new()
        {
            Timeout = new TimeSpan(0, 0, 5)
        }; //handler             
        httpClient.DefaultRequestHeaders.Accept.Clear();
        httpClient.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));
        //转为链接需要的格式       
        using HttpContent httpContent = JsonContent.Create(datajson);
        //请求       
        using var response = await httpClient.PostAsync(uri, httpContent)
                                             .ConfigureAwait(false);
        if (response.IsSuccessStatusCode)
        {
            return await response.Content.ReadAsStringAsync()
                                         .ConfigureAwait(false);
        }
        throw new Exception($"{uri}数据下载错误:{response.ReasonPhrase}");
    }

    public static async Task<string> HttpClientGetAsync(Uri url)
    {
        //在使用GB2312编码前需要先使用Encoding.RegisterProvider方法注册
        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        //服务器会返回GZip压缩后的数据,数据要求解压
        using HttpClientHandler handler = new()
        {
            AutomaticDecompression = DecompressionMethods.GZip
        };
        using HttpClient httpClient = new(handler)
        {
            Timeout = new TimeSpan(0, 0, 5)
        }; //handler         
        httpClient.DefaultRequestHeaders.Accept.Clear();
        httpClient.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("text/html"));
        //请求      
        using var response = await httpClient.GetAsync(url)
                                             .ConfigureAwait(false);        
        if (response.IsSuccessStatusCode)
        {
            return await response.Content.ReadAsStringAsync()
                                         .ConfigureAwait(false);
        }

        throw new Exception($"{url}数据下载错误:{response.ReasonPhrase}");
    }
}